/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.aierjun.ani.net.OkGo.download;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aierjun.ani.R;
import com.aierjun.ani.net.OkGo.DownloadUtils;
import com.aierjun.ani.net.OkGo.NumberProgressBar;
import com.aierjun.ani.utils.MPermission;
import com.aierjun.ani.utils.ToastUtil;
import com.aierjun.ani.widget.MyListView;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.task.XExecutor;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class DownloadActivity extends Activity implements XExecutor.OnAllTaskEndListener {
    private Float fraction = 0.0f;
    private TextView uploadDo, uploadOk;
    private FrameLayout upload_fragment_do, upload_fragment_ok;
    private MyListView recyclerView_do, recyclerView_ok;

    private DownloadAdapter adapter;
    private DownloadOverAdapter uploadOverAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uploadall_okgo);
        MPermission.with(this)
                .setPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .requestPermission();
        init();
        findView();
        initView();
    }

    private void init() {
        Intent intent = getIntent();
        String url = intent.getStringExtra("URL");
        String name = intent.getStringExtra("Name");
        HttpHeaders httpHeaders = (HttpHeaders) intent.getSerializableExtra("HttpHeaders");
        HttpParams httpParams = (HttpParams) intent.getSerializableExtra("HttpParams");
        String tag = intent.getStringExtra("Tag");
        DownloadManager downloadManager = DownloadManager.getInstance();
        List<Progress> list = downloadManager.getDownloading();
        for (int i = 0;i<list.size();i++){
            if (list.get(i).tag.equals(tag)){
                ToastUtil.showShort(this,"该下载已在任务中");
                return;
            }
        }
        DownLoadEntity downLoadEntity = new DownLoadEntity();
        downLoadEntity.setTag(tag);
        downLoadEntity.setFilePath(OkDownload.getInstance().getFolder());
        downLoadEntity.setStatus(2);
        downLoadEntity.setName(name);
        List<DownLoadEntity> downLoadEntityList = new ArrayList<>();//目前只支持一个
        downLoadEntityList.add(downLoadEntity);

        downLoadData(url,httpHeaders,httpParams,tag);
    }

    @MPermission.PermissionOK
    private void valdateSuccess() {
        Log.i("Ani", "权限通过");
    }

    @MPermission.PermissionFail
    public void validateFail() {
        Log.i("Ani", "上传 没有相应的权限");
    }

    private void findView() {
        recyclerView_do = (MyListView) findViewById(R.id.recyclerView_do);
        recyclerView_ok = (MyListView) findViewById(R.id.recyclerView_ok);
        uploadDo = (TextView) findViewById(R.id.upload_do);
        uploadOk = (TextView) findViewById(R.id.upload_ok);
        upload_fragment_do = (FrameLayout) findViewById(R.id.upload_fragment_do);
        upload_fragment_ok = (FrameLayout) findViewById(R.id.upload_fragment_ok);
    }

    //初始化View
    private void initView() {
        uploadDo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload_fragment_do.setVisibility(View.VISIBLE);
                upload_fragment_ok.setVisibility(View.GONE);
            }
        });
        uploadOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload_fragment_do.setVisibility(View.GONE);
                upload_fragment_ok.setVisibility(View.VISIBLE);
            }
        });
    }


    //下载任务
    private void downLoadData(final String url, HttpHeaders httpHeaders, HttpParams httpParams, String tag) {
        DownloadTask task = DownloadUtils.download(url, httpHeaders, httpParams, tag, new DownloadListener(tag) {
            @Override
            public void onStart(Progress progress) {

            }

            @Override
            public void onProgress(Progress progress) {
                Log.d("Ani onProgress", "总大小 " + (float) progress.totalSize / 1024 / 1024 + "M    速度  " + (float) progress.speed / 1024 / 1024 + " KB/s   当前大小  " + (float) progress.currentSize / 1024 / 1024 + "M   状态  " + progress.status + "  进度 " + (int) ((fraction / (float) progress.totalSize) * 100));
                setProgressBar((int) ((fraction / (float) progress.totalSize) * 100));
            }

            @Override
            public void onError(Progress progress) {

            }

            @Override
            public void onFinish(File file, Progress progress) {
                Log.d("Ani", progress.date + "" + progress.toString());
                setProgressBar(100);
            }

            @Override
            public void onRemove(Progress progress) {

            }
        });
        task.start();
    }

    public View getViewByPosition(int pos, ListView listView) {
        final int firstListItemPosition = listView.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition) {
            return listView.getAdapter().getView(pos, null, listView);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }

    //下载进度
    public void setProgressBar(int progress) {
        LinearLayout linearLayout = (LinearLayout) getViewByPosition(0, recyclerView_do);
        LinearLayout l = (LinearLayout) linearLayout.getChildAt(1);
        RelativeLayout relativeLayout = (RelativeLayout) l.getChildAt(1);
        TextView textView = (TextView) relativeLayout.getChildAt(0);
        textView.setText(progress + " / 100");
        NumberProgressBar numberProgressBar = (NumberProgressBar) l.getChildAt(2);
        numberProgressBar.setProgress(progress);
    }


    protected void onDestroy() {
        super.onDestroy();
        OkDownload.getInstance().removeOnAllTaskEndListener(this);
    }

    @Override
    public void onAllTaskEnd() {
        ToastUtil.showShort(this, "所有上传任务已结束");
    }


}

